/*
 * @Author: szx
 * @Date: 2022-04-21 13:43:36
 * @LastEditTime: 2022-04-21 13:55:40
 * @Description:
 * @FilePath: \leetcode\剑指offerII\078\078.js
 */
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
/**
 * @param {ListNode[]} lists
 * @return {ListNode}
 */
var mergeKLists = function (lists) {
    if (lists.length == 0) return null;
    let res = lists[0];
    for (let i = 1; i < lists.length; i++) {
        res = merge(res, lists[i]);
    }
    return res;
};

function merge(left, right) {
    const prev = new ListNode(-1);
    let cur = prev;
    while (left && right) {
        if (left.val < right.val) {
            cur.next = left;
            left = left.next;
        } else {
            cur.next = right;
            right = right.next;
        }
        cur = cur.next;
    }
    cur.next = left ? left : right;
    return prev.next;
}
